import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'HomePage',
    component: ()=>import('../views/Home/HomePage')
  },
  {
    path: '/article-list',
    name: 'ArticlePage',
    component: ()=>import('../views/Article/ArticlePage')
  },
  {
    path: '/article-dtail/:id',
    name: 'ArticleDetail',
    component: ()=>import('../views/Article/ArticleDetail')
  },
  /*后台管理路由*/
  {
    path: '/admin',
    name: 'amdin',
    component: ()=> import('../views/Admin/index'),
    redirect: '/admin/manage-blog',
    meta: { requireAuth: true },
    children:[
      {
        path: 'add-blog',
        name: 'addBlog',
        component: ()=> import('../views/Admin/AddBlog'),
        meta: { requireAuth: true }
      },
      {
        path: 'manage-blog',
        name: 'manageBlog',
        component: ()=> import('../views/Admin/ManageBlog'),
        meta: { requireAuth: true }
      },
      {
        path: 'edit-blog/:id',
        name: 'editBlog',
        component: ()=> import('../views/Admin/EditBlog'),
        meta: { requireAuth: true }
      },
      {
        path: 'post-result',
        name: 'Result',
        component: ()=> import('../views/Admin/Result')
      }
    ]
  },
  /*关于我*/
  {
    path: '/about',
    name: 'AboutMe',
    component: ()=> import('../views/AboutMe/About')
  },
  /*搜索界面*/
  {
    path: '/search/:keyWord',
    name: 'SearchPage',
    component: () => import('../views/SearchPage/SearchPage')
  },
  /*后台登录路由*/
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Admin/Login')
  },
  /*导航界面*/
  {
    path: '/nav-page',
    name: 'navPage',
    component: ()=> import('../views/NavPage/navPage')
  },
  /*404界面*/
  {
    path: "*",
    name: 'error',
    component: ()=> import('../views/Home/Error')
  }
]


const router = new VueRouter({
  routes
})

/*登录拦截*/
router.beforeEach((to, from, next) => {
  if (to.matched.some(res => res.meta.requireAuth)) { // 验证是否需要登陆
    if (sessionStorage.getItem('token')) { // 查询本地存储信息是否已经登陆
      next();
    } else {
      next({
        path: '/login', // 未登录则跳转至login页面
        query: {redirect: to.fullPath} // 登陆成功后回到当前页面，这里传值给login页面，to.fullPath为当前点击的页面
      });
    }
  } else {
    next();
  }
});

export default router
